package com.cloud.apis.user.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.cloud.apis.core.exception.CustomException;
import com.cloud.apis.core.model.*;
import com.cloud.apis.core.utils.PageInfoToPageDataConverterUtil;
import com.cloud.apis.core.web.ServiceCode;
import com.cloud.apis.message.task.MessageTask;
import com.cloud.apis.message.utils.MessageSendUtil;
import com.cloud.apis.user.db.dao.RoleMapper;
import com.cloud.apis.user.db.dao.UserMapper;
import com.cloud.apis.user.pojo.form.*;
import com.cloud.apis.user.service.IRoleService;
import com.cloud.apis.websocket.WebSocketServe;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 角色相关API接口业务层实现
 *
 * @Author YinXi
 * @Versin 1.0.0
 * @Date 2024/3/21
 */
@Slf4j
@Service
public class RoleService implements IRoleService {
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MessageTask messageTask;
    @Autowired
    private WebSocketServe webSocketServe;
    @Value("${custom-config.default-query-page-size}")
    private Integer defaultQueryPageSize;

    public RoleService() {
        log.info("【RoleService】");
    }

    @Override
    public Role searchRoleById(Long roleId) {
        return roleMapper.selectRoleById(roleId);
    }

    @Override
    public ArrayList<Role> list() {
        return roleMapper.getRolelist();
    }

    @Override
    public PageData<Role> listRole(RoleListForm form) {
        return listPage(form.getPageNum(),defaultQueryPageSize);
    }

    @Override
    public PageData<Role> listPage(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Role> list = roleMapper.getRolelist();
        PageInfo<Role> pageInfo = new PageInfo<>(list);
        return PageInfoToPageDataConverterUtil.convert(pageInfo);
    }

    @Override
    public Role addRole(AddRoleForm form) {
        if (roleMapper.selectRoleByAbbreviation(form.getAbbreviation())!=null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "该角色简称已存在");
        }
        int num = roleMapper.insertRole(form);
        if(num==0){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "添加角色失败");
        }
        return roleMapper.selectRoleById(form.getId());
    }

    @Override
    public void updateRole(UpdateRoleForm form) {
        if(roleMapper.selectRoleById(form.getId())==null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "该角色不存在");
        }
        Role role = roleMapper.selectRoleByAbbreviation(form.getAbbreviation());
        if(role!=null && !role.getId().equals(form.getId())){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "该角色简称已存在");
        }
        int num = roleMapper.updateRole(form);
        if(num==0){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "修改角色失败");
        }
    }

    @Override
    public void setEnable(EnableRoleForm form) {
        if (roleMapper.selectRoleById(form.getId())==null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "该角色不存在");
        }
        int num = roleMapper.updateRoleEnable(form);
        if(num==0){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "修改角色状态失败");
        }
    }

    @Override
    public PageData<Role> searchByName(Integer pageNum, Integer pageSize, SearchRoleForm form) {
        PageHelper.startPage(pageNum, pageSize);
        List<Role> list = roleMapper.searchByName(form);
        PageInfo<Role> pageInfo = new PageInfo<>(list);
        return PageInfoToPageDataConverterUtil.convert(pageInfo);
    }

    @Override
    public PageData<Role> listSearchResult(SearchRoleForm form) {
        return searchByName(form.getPageNum(),defaultQueryPageSize,form);
    }

    @Override
    public PageData<Permission> listPermissions(RolePermissionPageForm form) {
        return listRolePermission(form.getPageNum(),defaultQueryPageSize,form);
    }

    @Override
    public PageData<Permission> listRolePermission(Integer pageNum, Integer pageSize, RolePermissionPageForm form) {
        PageHelper.startPage(pageNum, pageSize);
        List<Permission> list = roleMapper.selectPermissionsByRoleId(form);
        PageInfo<Permission> pageInfo = new PageInfo<>(list);
        return PageInfoToPageDataConverterUtil.convert(pageInfo);
    }

    @Override
    public void addPermissions(RolePermissionForm form) {
        if(roleMapper.selectRoleById(form.getRoleId())==null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "该角色不存在");
        }
        ArrayList<RolePermission> rolePermissionList = new ArrayList<>();
        for (int i = 0; i < form.getPermissionIds().length; i++) {
            rolePermissionList.add(new RolePermission(form.getRoleId(),form.getPermissionIds()[i]));
        }
        int num = roleMapper.insertRolePermission(rolePermissionList);
        if(num==0){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "添加权限失败");
        }
    }

    @Override
    public void deleteRolePermission(RolePermissionIdForm form) {
        if(!roleMapper.selectRolePermissionById(form)){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "该关联不存在");
        }
        int num = roleMapper.deleteRolePermission(form);
        if(num==0){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "取消关联失败");
        }
    }

    @Override
    public PageData<Permission> searchByRolePermissionName(Integer pageNum, Integer pageSize, RolePermissionSearchForm form) {
        PageHelper.startPage(pageNum, pageSize);
        List<Permission> list = roleMapper.searchByRolePermissionName(form);
        PageInfo<Permission> pageInfo = new PageInfo<>(list);
        return PageInfoToPageDataConverterUtil.convert(pageInfo);
    }

    @Override
    public PageData<Permission> searchRolePermission(RolePermissionSearchForm form) {
        return searchByRolePermissionName(form.getPageNum(),defaultQueryPageSize,form);
    }

    @Override
    public ArrayList<Role> searchOtherRoles(Long id) {
        if(userMapper.selectUserById(id)==null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "该用户不存在");
        }
        return roleMapper.selectOtherRoles(id);
    }

    @Override
    public void setRoles(UserRoleForm form) {
        if(userMapper.selectUserById(form.getId())==null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "该用户不存在");
        }
        //判断角色是否存在
        for(Long roleId : form.getRoleIds()){
            if(roleMapper.selectRoleById(roleId)==null){
                throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(),"角色不存在");
            }
        }
        //关联用户和角色
        int exNum = userMapper.insertUserRole(form.getId(), form.getRoleIds());
        if(exNum<=0){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(),"出现了异常请及时联系系统管理员");
        }
        MessageSendUtil.sendSimpleMessage(messageTask,form.getId(),"系统消息","您的角色已经增添,请您重新登录后拥有");
        webSocketServe.sendMessage(form.getId());
    }

    @Override
    public ArrayList<Role> getListRoles(Long id) {
        if(userMapper.selectUserById(id)==null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "该用户不存在");
        }
        return roleMapper.selectRoleByUserId(id);
    }

    @Override
    public void deleteRoleUsers(UserRoleForm form) {
        if(userMapper.selectUserById(form.getId())==null){
            throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(), "该用户不存在");
        }
        //判断角色是否存在
        for(Long roleId : form.getRoleIds()){
            if(roleMapper.selectRoleById(roleId)==null){
                throw new CustomException(ServiceCode.ERROR_BAD_REQUEST.getValue(),"角色不存在");
            }
        }
        int num = roleMapper.deleteUserRole(form);
    }
}
